import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
//导入页面
import './pages/home.dart';
import './pages/message.dart';
import './pages/welfare.dart';
//导入组件
import './widget/my_drawer.dart';
//导入工具类
import './util/search_delegate.dart';


class AppLayout extends StatefulWidget {
  const AppLayout({Key? key}) : super(key: key);

  @override
  _AppLayoutState createState() => _AppLayoutState();
}

class _AppLayoutState extends State<AppLayout> {
  List<Widget> pages = [];
  int _currentIndex = 0;
  late String _title;
  List<Map> tabBars = [
    {'icon': Icons.home,  'title': '首页'},
    {'icon': Icons.message, 'title': '消息'},
    {'icon': Icons.map, 'title': '福利'},
  ];
  late PageController _pageController;


//  初始化页面
  @override
  void initState() {
    pages..add(const Home())..add(const Message())..add(const Welfare());
    _title = tabBars[0]['title'];
    _pageController = PageController(initialPage: 0, keepPage: true);
    super.initState();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:  Text(_title),
        // leading:  Builder(builder: (context) {
        //   return IconButton(
        //     icon: const Icon(Icons.menu),
        //     onPressed: () {
        //       Scaffold.of(context).openDrawer();
        //     }
        //   );
        // }),
        actions: [
          // 搜索按钮
          IconButton(
            onPressed: (){
              // 展示搜索
              showSearch(context: context, delegate: SearchBarDelegate());
            },
            icon: const Icon(Icons.search)
          )
        ],
      ),
      drawer: const MyDrawer(),
      // 简单的，不能通过左右滑动切换页面
      // body: pages[_currentIndex],
      // 可以左右滑动切换页面
      body: PageView(
        // 控制器
        controller: _pageController,
        // 子页面
        children: pages,
        onPageChanged: (index){
          setState(() {
            _currentIndex = index;
            _title = tabBars[index]['title'];
          });
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index){
          _pageController.jumpToPage(index);
          setState(() {
            _currentIndex = index;
            _title = tabBars[index]['title'];
          });
        },
        items: tabBars.map((item) {
          return BottomNavigationBarItem(
            icon: Icon(item['icon']),
            label: item['title'],
          );
        }).toList(),
      ),
    );
  }
}
